#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#include <memory.h>

#include "pthread_cond.h"

int condition_var_init(struct condition_var *cond)
{
	memset(cond, 0, sizeof(struct condition_var));
    pthread_mutex_init(&cond->mutex, NULL);
    pthread_cond_init(&cond->cond, NULL);
	cond->init_flag = 1;
	return 0;
}

int condition_var_deinit(struct condition_var *cond)
{
    pthread_mutex_destroy(&cond->mutex);
    pthread_cond_destroy(&cond->cond);
	cond->init_flag = 0;
	memset(cond, 0, sizeof(struct condition_var));
	return 0;
}

int condition_var_complete(struct condition_var *cond)
{  
	if (cond->init_flag == 0) {
		fprintf(stderr, "condition var is not init\r\n");
		return -1;
	}
	pthread_mutex_lock(&cond->mutex);
	cond->condition = 1;
    /* do something that might make condition true */
    pthread_cond_signal(&cond->cond);
    pthread_mutex_unlock(&cond->mutex);
	return 0;
}

int condition_var_wait(struct condition_var *cond)
{  
	if (cond->init_flag == 0) {
		fprintf(stderr, "condition var is not init\r\n");
		return -1;
	}
    pthread_mutex_lock(&cond->mutex);
    while (cond->condition == 0)
        pthread_cond_wait(&cond->cond, &cond->mutex);
    /* do something that requires holding the mutex and condition is true */
    pthread_mutex_unlock(&cond->mutex);
	return 0;
}

int condition_var_reset(struct condition_var *cond)
{  
	if (cond->init_flag == 0) {
		fprintf(stderr, "condition var is not init\r\n");
		return -1;
	}
    pthread_mutex_lock(&cond->mutex);
	cond->condition = 0;
    pthread_mutex_unlock(&cond->mutex);
	return 0;	
}

